export type position = [number, number];

/** 处理两点之间的短线问题, 输入为矩阵 index*/
export const pathFill = (pointA: position, pointB: position) => {
    const [xA, yA] = pointA;
    const [xB, yB] = pointB;
    const isNeighbor = isNeigh(xA, yA, xB, yB);
    if (isNeighbor) {
        return [pointB];
    } else {
        // 具体方式是使用两点式方程求出两点间的连线，然后填充上去
        const line = [] as position[];
        const diff = [xA - xB, yA - yB];
        const axisName = Math.abs(diff[0]) >= Math.abs(diff[1]) ? 0 : 1;
        const symbol = diff[axisName] > 0 ? 1 : -1;
        let k = (yA - yB) / (xA - xB);
        const maxK = 1000000;
        const b = yA - k * xA;
        const edge = Math.abs(diff[axisName]);
        // 根据长轴进行遍历
        for (let axis = 0; axis <= edge; axis++) {
            let trueX, trueY;
            const target = pointB[axisName] + axis * symbol;
            if (axisName === 0) {
                trueX = target;
                trueY = Math.floor(k * trueX + b);
            } else {
                trueY = target;
                // 在竖直的状态时会导致 k 值无限，所以 k 大于一定量时直接赋值为 xB
                trueX =
                    k > maxK || k < -maxK ? xB : Math.floor((trueY - b) / k);
            }
            line.push([trueX, trueY]);
        }
        return [...line, pointB];
    }
};
function isNeigh(xA: number, yA: number, xB: number, yB: number) {
    const around = [
        [xA, yA],
        [xA - 1, yA],
        [xA + 1, yA],
        [xA, yA - 1],
        [xA, yA + 1],
        [xA - 1, yA - 1],
        [xA + 1, yA + 1],
        [xA + 1, yA - 1],
        [xA - 1, yA + 1],
    ];
    const isNeighbor = around.some(([x, y]) => {
        return x === xB && y === yB;
    });
    return isNeighbor;
}
